<script setup>
import {ref, reactive, onMounted} from "vue";
import {Edit, Plus, View, Delete} from "@element-plus/icons";
import {ElMessage, ElMessageBox} from "element-plus";

const emit = defineEmits(['view-keywords'])

const dialogFormVisible = ref(false);
// 定义默认表单值
const defaultForm = {
  name: "",
  color: "rgba(19, 206, 102, 0.8)"
};
const form = reactive({...defaultForm});
const keywordGroups = ref([]);
// 添加一个响应式变量来跟踪当前编辑的分组ID
const editingGroupId = ref(null);

const openDialogForm = () => {
  // 重置编辑状态
  editingGroupId.value = null;
  dialogFormVisible.value = true;
};

const closeDialogForm = () => {
  // 重置表单为默认值
  Object.assign(form, defaultForm);
  dialogFormVisible.value = false;
  editingGroupId.value = null;
};

const saveDialogForm = () => {
  if (editingGroupId.value) {
    // 编辑模式
    chrome.storage.local.get(['groups'], (result) => {
      const groups = result.groups || [];
      const index = groups.findIndex(group => group.id === editingGroupId.value);
      if (index !== -1) {
        // 更新分组信息
        groups[index] = {...groups[index], ...form};
        chrome.storage.local.set({groups}, () => {
          keywordGroups.value = groups;
          ElMessage.success("分组更新成功");
          closeDialogForm();
          console.log("分组更新成功，当前所有分组:", groups);
        });
      }
    });
  } else {
    // 生成唯一ID
    const newGroup = {
      id: Date.now(), // 或使用其他唯一ID生成方式
      ...form
    };

    // 获取现有分组数据
    chrome.storage.local.get(['groups'], (result) => {
      const groups = result.groups || [];
      groups.push(newGroup);

      // 存储更新后的分组列表
      chrome.storage.local.set({
        groups: groups
      }, () => {
        keywordGroups.value = groups;
        ElMessage.success("分组保存成功");
        closeDialogForm();
        console.log("分组保存成功，当前所有分组:", groups);
      });
    });
  }
}

const getGroupList = () => {
  // 获取分组列表
  chrome.storage.local.get(['groups'], (result) => {
    keywordGroups.value = result.groups || [];
    console.log("当前所有分组:", keywordGroups.value);
  });
};

const editGroup = (groupId) => {
  // 查找要编辑的分组
  const groupToEdit = keywordGroups.value.find(group => group.id === groupId);
  if (groupToEdit) {
    // 将分组数据填充到表单
    form.name = groupToEdit.name;
    form.color = groupToEdit.color;
    // 设置当前编辑的分组ID
    editingGroupId.value = groupId;
    dialogFormVisible.value = true;
  }
  console.log("edit group");
};

const deleteGroup = (groupId) => {
  // 添加确认弹窗，提示用户会同时删除分组下的关键词
  ElMessageBox.confirm(
      '确定要删除这个分组吗？此操作会同时删除该分组下的所有关键词，且不可撤销。',
      '确认删除分组',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 同时获取分组和关键词数据
        chrome.storage.local.get(['groups', 'keywords'], (result) => {
          const groups = result.groups || [];
          const keywords = result.keywords || [];

          // 1. 删除分组
          const updatedGroups = groups.filter(group => group.id !== groupId);

          // 2. 删除该分组下的所有关键词
          const updatedKeywords = keywords.filter(keyword => keyword.groupId !== groupId);

          // 3. 同时更新分组和关键词数据
          chrome.storage.local.set({
            groups: updatedGroups,
            keywords: updatedKeywords
          }, () => {
            // 更新本地响应式数据
            keywordGroups.value = updatedGroups;

            // 如果当前有监听关键词列表的组件，也需要更新
            // 这里可以触发一个事件或者调用回调来更新关键词列表
            if (typeof onGroupDeleted === 'function') {
              onGroupDeleted(groupId);
            }

            ElMessage.success("分组及分组下关键词删除成功");
            console.log("分组删除成功，当前所有分组:", updatedGroups);
            console.log("关键词同步删除，剩余关键词数量:", updatedKeywords.length);
          });
        });
      })
      .catch(() => {
        // 取消删除
        ElMessage.info('已取消删除');
      });
};

const viewKeywordOfGroup = (groupId) => {
  // 发送事件到父组件，让父组件切换到关键词标签页并传递组ID
  emit('view-keywords', groupId);
  console.log("view keyword of group", groupId);
};

onMounted(() => {
  getGroupList();
});
</script>

<template>
  <div class="container">
    <div class="header">
      <el-button type="primary" @click="openDialogForm">
        <el-icon>
          <Plus/>
        </el-icon>
        新建分组
      </el-button>
    </div>

    <div class="groups-grid">
      <div
          v-for="item in keywordGroups"
          :key="item.id"
          class="group-card"
      >
        <div class="card-header">
          <div class="color-indicator" :style="{ backgroundColor: item.color }"></div>
          <span class="group-name" :title="item.name">{{ item.name }}</span>
        </div>
        <div class="card-actions">
          <el-tooltip content="编辑分组" placement="top">
            <el-button size="small" type="primary" link @click="editGroup(item.id)">
              <el-icon>
                <Edit/>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除分组" placement="top">
            <el-button size="small" type="danger" link @click="deleteGroup(item.id)">
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="查看关键词" placement="top">
            <el-button size="small" type="primary" link @click="viewKeywordOfGroup(item.id)">
              <el-icon>
                <View/>
              </el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>

    <el-dialog :title="editingGroupId ? '编辑分组' : '新建分组'" v-model="dialogFormVisible" width="500px">
      <el-form :model="form">
        <el-form-item label="分组颜色">
          <el-color-picker v-model="form.color" show-alpha></el-color-picker>
        </el-form-item>
        <el-form-item label="分组名称">
          <el-input v-model="form.name" placeholder="请输入分组名称" maxlength="20" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialogForm">取 消</el-button>
          <el-button type="primary" @click="saveDialogForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.group-card {
  display: flex;
  flex-direction: column;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  min-height: 100px;
}

.group-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #409eff;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  flex: 1;
}

.color-indicator {
  width: 24px;
  height: 24px;
  border-radius: 6px;
  border: 2px solid #f0f0f0;
  flex-shrink: 0;
}

.group-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }

  .groups-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 12px;
  }

  .group-card {
    padding: 12px;
    min-height: 90px;
  }

  .group-name {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .groups-grid {
    grid-template-columns: 1fr;
  }

  .card-actions {
    justify-content: space-around;
  }
}

/* 空状态样式 */
.groups-grid:empty::before {
  content: "暂无分组，点击上方按钮创建第一个分组";
  display: block;
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  font-size: 14px;
  grid-column: 1 / -1;
}
</style>